import React, { Key, useEffect, useState } from "react";

import { Tree, Card, Row, Col, Tag, Pagination, Table, message } from "antd";

import { useParams } from "react-router-dom";

import {
  findScheduleListRequest,
  getHospitalDepartmentListRequest,
  getHospitalScheduleListRequest,
} from "@/api/hospital/hospitalList";

import type {
  hospitalDepartmentReturnType,
  bookingScheduleListType,
  findScheduleListType,
} from "@/api/hospital/model/hospitalListTypes";

export default function HospitalSchedule() {
  const { hoscode } = useParams();
  // console.log(hoscode);

  const [page, setPage] = useState(1);
  const [limit, setLimit] = useState(3);
  const [total, setTotal] = useState(0);
  const [hosName, setHosName] = useState("");
  const [departmentList, setDepartmentList] =
    useState<hospitalDepartmentReturnType>([]);
  const [scheduleRuleList, setScheduleRuleList] =
    useState<bookingScheduleListType>([]);
  const [sourceData, setSourceData] = useState<findScheduleListType>([]);
  const [depCode, setDepCode] = useState("");
  const [workDate, setWorkDate] = useState("");
  const [isLoading, setIsLoading] = useState(false);

  const getHosDepartment = async () => {
    const result = await getHospitalDepartmentListRequest(hoscode as string);
    setDepartmentList(result);
    return result;
  };

  const getScheduleList = async (
    page: number,
    limit: number,
    depCode: string
  ) => {
    const result = await getHospitalScheduleListRequest({
      page,
      limit,
      hoscode: hoscode as string,
      depcode: depCode,
    });
    setScheduleRuleList(result.bookingScheduleList);
    setTotal(result.total);
    return result;
  };

  const findScheduleList = async (depcode: string, workDate: string) => {
    const result = await findScheduleListRequest(
      hoscode as string,
      depcode,
      workDate
    );
    setWorkDate(workDate);
    setSourceData(result);
  };

  useEffect(() => {
    setIsLoading(true);
    const initData = async () => {
      const hosDepartmentList = await getHosDepartment();
      const initDepcode = (
        hosDepartmentList[0].children as hospitalDepartmentReturnType
      )[0].depcode;
      setDepCode(initDepcode);
      const scheduleRuleList = await getScheduleList(page, limit, initDepcode);
      const initWorkDate = scheduleRuleList.bookingScheduleList[0].workDate;
      setWorkDate(initWorkDate);
      await findScheduleList(initDepcode, initWorkDate);
      setIsLoading(false);
    };
    initData();
  }, []);

  const columns = [
    {
      title: "序号",
      render(_: any, __: any, index: number) {
        return index + 1;
      },
    },
    {
      title: "职称",
      dataIndex: "title",
    },
    {
      title: "号源时间",
      dataIndex: "workDate",
    },
    {
      title: "可预约数",
      dataIndex: "reservedNumber",
    },
    {
      title: "挂号费用",
      dataIndex: "amount",
    },
    {
      title: "擅长技能",
      dataIndex: "skill",
    },
  ];


 const pageChangeHandle = async (page: number, pageSize: number) => {
    setPage(page);
    setLimit(pageSize);

    const scheduleRuleResult = await getScheduleList(page, pageSize, depCode);

    const firstWorkDate = scheduleRuleResult.bookingScheduleList[0].workDate;
    setWorkDate(firstWorkDate);

    findScheduleList(depCode, firstWorkDate);
  };

  const treeSelectHandle = async (dopCodeArr: Key[]) => {
    if (dopCodeArr.length===0) return;
    try {
      const depcode=dopCodeArr[0] as string
      setDepCode(depcode)
      const scheduleList = await getScheduleList(
        page,
        limit,
        depcode
      );
      const firstWorkDate = scheduleList.bookingScheduleList[0].workDate;
      findScheduleList(depcode, firstWorkDate);
    } catch (error) {
      message.error("没有数据");
      setSourceData([]);
    }
  };

   const tagClickHandle = (workDate: string) => {
    return () => {
      setWorkDate(workDate)
      findScheduleList(depCode, workDate);
    };
  };
  return (
    <div>
      <Card>
        <p>选择:{hosName}/多发性硬化专科门诊/2022-04-08</p>
        <Row gutter={20}>
          <Col span={5}>
            <Tree
              expandedKeys={["a4e171f4cf9b6816acdfb9ae62c414d7"]}
              treeData={departmentList as []}
              fieldNames={{ title: "depname", key: "depcode" }}
              style={{
                height: "480px",
                overflow: "auto",
                border: "1px solid #DDD",
              }}
              onSelect={treeSelectHandle}
            />
          </Col>
          <Col span={18}>
            <div style={{ marginBottom: 20 }}>
              {scheduleRuleList.map((item) => {
                return (
                  <Tag
                    key={item.workDate}
                    color="success"
                    onClick={tagClickHandle(item.workDate)}
                    style={{
                      cursor: "pointer",
                      backgroundColor: item.workDate === workDate ? "#bfa" : "",
                    }}
                  >
                    <p>{`${item.workDate}/${item.dayOfWeek}`}</p>
                    <p>{`${item.availableNumber}/${item.reservedNumber}`}</p>
                  </Tag>
                );
              })}
            </div>

            <div>
              <Pagination
                style={{ marginBottom: 20 }}
                current={page}
                pageSize={limit}
                total={total}
                onChange={pageChangeHandle}
              />
            </div>

            <Table
              rowKey="id"
              bordered
              pagination={false}
              columns={columns}
              dataSource={sourceData}
              loading={isLoading}
            />
          </Col>
        </Row>
      </Card>
    </div>
  );
}
